package com.pet.framework.util;


import java.util.ArrayList;
import java.util.HashMap;
import java.util.List;
import java.util.Map;

import com.pet.framework.constant.Tree;
import com.pet.framework.constant.TreeNode;
import com.pet.server.bo.role.RoleService;
import com.pet.server.po.Constant;



public class ConstantUtil {

	public static ConstantUtil util;
	public static List<Constant> list=new ArrayList<Constant>();
	public Map<String, Constant> map = new HashMap<String, Constant>();
	public static boolean init = false;
	public Tree<Constant> tree;
	
	
	
	public synchronized static ConstantUtil getInstance() {
		if(null==util){
			util=new ConstantUtil();
		}
		return util;
	}
	public void init(){
		if(!init){
			createTree();
			init=true;
		}
	}
	public TreeNode<Constant> findNode(String code){
		init();
		Constant c = map.get(code);
		return tree.findNode(c);
	}
	
	public void createTree(){
		RoleService roleService = SpringUtil.getBean("roleService", RoleService.class);
		list=roleService.queryAllConstants();
		put();
		tree = new Tree<Constant>();
		Constant root = new Constant();
		root.setCode("0");
		tree.addNode(null, root);
		addTreeNode(tree.root);
	}
	public void addTreeNode(TreeNode<Constant> node){
		List<Constant> l = queryChildNode(node.t);
		for(Constant c:l){
			tree.addNode(node, c);
		}
		for(int i=0;i<node.nodelist.size();i++){
			addTreeNode(node.nodelist.get(i));
		}
	}
	public Constant getConstant(String key){
	    init();
		return map.get(key);
	}
	public void put(){
		for(Constant c:list){
			map.put(c.getCode(), c);
		}
	}
	
	
	public List<Constant> queryChildNode(Constant node){
		List<Constant> l = new ArrayList<Constant>();
		for(Constant c:list){
			if(StringUtil.equals(node.getCode(), c.getPcode())){
				l.add(c);
				//list.remove(c);
			}
		}
		return l;
	}
	
	
	
	
	
	
	
}
